<?php
class CouponAction extends CommonAction {
	
	function _initialize() {
		parent::_initialize();
		
		$type_list = coupon_type();
		$this->assign('type_list',$type_list);
		
		$merchant_list = M('Merchant')->where('status=1')->getField('id,name');
		$this->assign('merchant_list',$merchant_list);
	}
	
	//过滤查询字段
	function _filter(&$map){
		if(I('type_id'))
			$map['type_id'] = array('eq',I('type_id'));
		else
			unset($map['type_id']);
		
		if(I('merchant_id'))
			$map['merchant_id'] = array('eq',I('merchant_id'));
		else
			unset($map['merchant_id']);
		
		if(I('number'))
			$map['number'] = array('eq',I('number'));
		else
			unset($map['number']);
		
		if(I('s_is_used')){
			$map['is_used'] = array('eq',I('s_is_used')-1);
			$this->assign('s_is_used',I('s_is_used'));
		}
		
		if(I('s_is_actived')){
			$map['is_actived'] = array('eq',I('s_is_actived')-1);
			$this->assign('s_is_actived',I('s_is_actived'));
		}
		
		if(I('s_start_time')){
			$map['actived_time'] = array('egt',strtotime(I('s_start_time')));
			$this->assign('s_start_time',strtotime(I('s_start_time')));
		}
		 
		if(I('s_end_time')){
			$map['actived_time'] = array('elt',strtotime(I('s_end_time')));
			$this->assign('s_end_time',strtotime(I('s_end_time')));
		}
		 
		if(I('s_start_time') && I('s_end_time')){
			$map['actived_time'] = array(array('egt',strtotime(I('s_start_time'))),array('elt',strtotime(I('s_end_time'))),'and');
		}
		
		if(I('s_status')){
			$map['status'] = array('eq',I('s_status')-1);
			$this->assign('s_status',I('s_status'));
		}
		//v($map);
	}
	
	function index(){
		if(I('merchant_id'))
			$this->assign('merchant_id',I('merchant_id'));
		if(I('type_id'))
			$this->assign('type_id',I('type_id'));
		if(I('number'))
			$this->assign('number',I('number'));
		
		//列表过滤器，生成查询Map对象
		$map = $this->_search();
		if (method_exists($this, '_filter')) {
			$this->_filter($map);
		}
		 
		$name = $this->getActionName();
		 
		$model = D($name);
		if (!empty($model)) {
			 
			//排序字段 默认为主键名
			if (isset($_REQUEST ['_order'])) {
				$order = $_REQUEST ['_order'];
			} else {
				$order = !empty($sortBy) ? $sortBy : $model->getPk();
			}
			//排序方式默认按照倒序排列
			//接受 sost参数 0 表示倒序 非0都 表示正序
			if (isset($_REQUEST ['_sort'])) {
				$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
			} else {
				$sort = $asc ? 'asc' : 'desc';
			}
			//取得满足条件的记录数
			$count = $model->where($map)->count('id');
		
			if ($count > 0) {
				import("@.ORG.Util.Page");
				//创建分页对象
				if (!empty($_REQUEST ['listRows'])) {
					$listRows = $_REQUEST ['listRows'];
				} else {
					$listRows = '';
				}
				$p = new Page($count, $listRows);
		
				//分页查询数据
				if(I('export')){
					//到处不分页
					$voList = $model->where($map)->order("`" . $order . "` " . $sort)->select();
				}else{
					$voList = $model->where($map)->order("`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
				}
		
				//分页跳转的时候保证查询条件
				foreach ($map as $key => $val) {
	    			if (!is_array($val)) {
	                    $p->parameter .= "$key=" . urlencode($val) . "&";
	                }else{
	                	$p->parameter .= "&$key=" . urlencode($val[1]);
	                }
    			}
    			
    			//v($p->parameter);
				
				
				//分页显示
				$page = $p->show();
				//列表排序显示
				$sortImg = $sort; //排序图标
				$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
				$sort = $sort == 'desc' ? 1 : 0; //排序方式
				//模板赋值显示
				$this->assign('list', $voList);
				$this->assign('sort', $sort);
				$this->assign('order', $order);
				$this->assign('sortImg', $sortImg);
				$this->assign('sortType', $sortAlt);
				$this->assign("page", $page);
			}
			Cookie::set('_currentUrl_', __SELF__);
		}
		
		if(I('export')){
		
			$content = iconv("utf-8","gbk","货券编号,货券类型,货券价格,销售信息,销售时间,使用状态,货券状态");
			$content = $content . "\n";
		
			$coupon_value=array();
			foreach($voList as $vo){
				$coupon_value['number'] = '"' . iconv('utf-8','gbk',$vo['number']) . '"';
				$coupon_value['type_name'] = '"' . iconv('utf-8','gbk',getCouponType($vo['id'])) . '"';
				$coupon_value['type_price'] = '"' . iconv('utf-8','gbk',getCouponPrice($vo['id'])) . '"';
				$merchant_name = getMerchantName($vo['merchant_id']);
				$coupon_value['sold'] = $vo['is_actived'] ? '"' . iconv('utf-8','gbk','由'.$merchant_name.'销售')  . '"' : '"' . iconv('utf-8','gbk','未销售') . '"';
				$coupon_value['sold_time'] = iconv('utf-8','gbk',toDate($vo['sold_time'],'y-m-d'));
				$coupon_value['is_used'] = $vo['is_used'] ? '"' . iconv('utf-8','gbk','已使用')  . '"' : '"' . iconv('utf-8','gbk','未使用') . '"';
				$coupon_status = $vo['status'] ? '启用':'禁用';
				$coupon_value['status'] = '"' . iconv('utf-8','gbk',$coupon_status) . '"';
				 
				$content .= implode(",", $coupon_value) . "\n";
			}
			
			//v($coupon_value);
			
			header("Content-Disposition: attachment; filename=coupon_list.csv");
			echo $content;exit;
		}
		 
		$this->display();
	}
	
	function _before_insert(){
		if(I('password')){
			$old_password = I('password');
			$_POST['salt'] = randomkeys(4);
			$_POST['password'] = md5(md5($old_password).$_POST['salt']);
			
			$show_passwd = count($old_password) - 5;	//扣除隐藏的4位 从0开始多减一位
			$_POST['password_show'] = substr($old_password, 0, $show_passwd).'****';
		}	
	}
	
	function _before_update(){
		if(I('password')){
			$old_password = I('password');
			$_POST['salt'] = randomkeys(4);
			$_POST['password'] = md5(md5($old_password).$_POST['salt']);
			$show_passwd = count($old_password) - 5;	//扣除隐藏的4位 从0开始多减一位
			$_POST['password_show'] = substr($old_password, 0, $show_passwd).'****';
		}else{
			unset($_POST['password']);	//留空不修改
		}
	}
	
	//激活
	public function active()
	{
		$coupon_info = M('Coupon')->find(I('id'));
		$this->assign('vo',$coupon_info);
		
		$merchant_list = getMerchant();
		$this->assign('merchant_list',$merchant_list);
	    $this->display();
	}

	public function doactive(){
		 
		$data['merchant_id'] = $merchant_id = I('merchant_id');
		$data['sold_time'] = $sold_time = strtotime(I('sold_time'));
		$data['remark'] = $remark = I('remark');
		$data['id'] = I('id');
		$data['actived_time'] = time();
		$data['is_actived'] = 1;
		if(!$merchant_id){
			$this->error('请选择销售商！');
		}
		if(!$sold_time){
			$this->error('请填写销售时间！');
		}
		$savereturn = M('Coupon')->save($data);
	
		if($savereturn){
			$this->success('激活成功！',U('Coupon/index',array('i'=>rand(10000,99999))));
		}else{
			$this->error('激活失败！');
		}
	}
	
	//取消激活
	public function cancle_active(){
		
		$data['id'] = $id = I('id');
		
		//已经使用无法取消
		$is_used = M('Coupon')->where("id=".$id)->getField('is_used');
		if($is_used > 0){
			$this->error('该券已被使用，取消激活失败！');
		}
		
		$data['actived_time'] = '';
		$data['merchant_id'] = '';
		$data['sold_time'] = '';
		$data['remark'] = '';
		$data['is_actived'] = 0;
		$savereturn = M('Coupon')->save($data);
	
		if($savereturn){
			$this->success('取消激活成功！',U('Coupon/index',array('i'=>rand(10000,99999))));
		}else{
			$this->error('取消激活失败！');
		}
	}
	
	//下载文件格式
	public function export_csv()
	{
		$content = iconv("utf-8","gbk","卡类别,卡号,密码");
		$content .= "\n";
		$content .= iconv("utf-8","gbk","卡类别请查看货券类型管理页面（例：3888） 卡号限制10-12位 密码限制6-8位  **导入时请删除本行**");
		$content .= "\n";
		
		header("Content-Disposition: attachment; filename=coupon.csv");
		echo $content;
		exit();
	}
	
	//导入文件
	public function export()
	{
		setlocale(LC_ALL,'zh_CN');
		//验证密码
		
		$this->_upload();

		$file = fopen(APP_PATH.'../Uploads'.$_POST['coupon_list'],'r');
		$index=0;
		while ($data = fgetcsv($file))   //每次读取CSV里面的一行内容
		{
			$index++;
			if($index == 1) continue;
			
			if($data[1]){
			    $coupon_list[] = $data;
			    //券号去重
			    $coupon_number_list[] = $data[1];
			}
		}
		
		if(!$coupon_list){
			$this->error('数据为空，请返回修改！');
		}
        
		//v($coupon_number_list);d
		if(count(array_unique($coupon_number_list)) != count($coupon_list)){
		    $this->error('卡号列表有重复项，请先删除！');
		}

		$coupun_model = D('Coupon');
		
		//先全部检查一遍
		foreach($coupon_list as $k=>$v)
		{
			$coupon_data['number'] = mb_convert_encoding($v[1], "UTF-8", "GBK");
			$coupon_data['type_id'] =  M('Coupontype')->where('name="'.mb_convert_encoding($v[0], "UTF-8", "GBK").'"')->getField('id');
			
			//v($coupon_list);
			
			if(!$coupon_data['type_id'])
				$this->error('货券类型输入错误'.'--第'.($k+1).'条数据');
			
			$old_password = mb_convert_encoding($v[2], "UTF-8", "GBK");
			
			if($old_password){
				$coupon_data['salt'] = randomkeys(4);
				$coupon_data['password'] = md5(md5($old_password).$coupon_data['salt']);
				
				$show_passwd = count($old_password) - 5;	//扣除隐藏的4位 从0开始多减一位
				$coupon_data['password_show'] = substr($old_password, 0, $show_passwd).'****';
			}
			$coupon_data['create_time'] = time();
			$coupon_data['status'] = 1;
			
			//v($coupon_data);
			if (false === $coupun_model->create($coupon_data)) {
				$this->error($coupun_model->getError().'--第'.($k+1).'条数据');
			}
			
			$coupon_data_arr[] = $coupon_data;	
		}

		if($coupon_data_arr){
			
			$return = $coupun_model->addAll($coupon_data_arr);
			
			if($return) $this->success('导入成功！', U("Coupon/index",array('v'=>time())));
			
		}else{
			$this->error('数据为空，导入失败！');
		}
	}
	
	//下载文件格式
	public function active_csv()
	{
		$content = iconv("utf-8","gbk","卡号,销售商ID,销售时间");
		$content .= "\n";
		$content .= iconv("utf-8","gbk","销售商ID请查看销售商管理页面 销售时间格式（例：2014/9/23）  **导入时请删除本行**");
		$content .= "\n";
		header("Content-Disposition: attachment; filename=active.csv");
		echo $content;
		exit();
	}
	
	//导入文件
	public function doactive_csv()
	{
		setlocale(LC_ALL,'zh_CN');
		//验证密码
		
		$this->_upload();

		$file = fopen(APP_PATH.'../Uploads'.$_POST['coupon_list'],'r');
		$index=0;
		while ($data = fgetcsv($file))   //每次读取CSV里面的一行内容
		{
			$index++;
			if($index == 1) continue;
			
			if($data[0]){
			    $coupon_list[] = $data;
			    //券号去重
			    $coupon_number_list[] = $data[0];
			}
		}
		
		if(!$coupon_list){
			$this->error('数据为空，请返回修改！');
		}

		if(count(array_unique($coupon_number_list)) != count($coupon_list))
			$this->error('卡号列表有重复项，请先删除！');
		
		$coupun_model = D('Coupon');
		
		//先全部检查一遍
		foreach($coupon_list as $k=>$v)
		{
			$coupon_data['number'] = mb_convert_encoding($v[0], "UTF-8", "GBK");
			
			$coupon_info = M('Coupon')->where('number="'.$coupon_data['number'].'"')->field('id,status')->find();
		
			if($coupon_info['status'] <= 0 ){
				$this->error('该优惠券已被禁用'.'--第'.($k+1).'条数据');
			}
			
			$coupon_data['id'] = $coupon_info['id'];
			
			$coupon_data['merchant_id'] = mb_convert_encoding($v[1], "UTF-8", "GBK");
			
			$merchant_count =  M('Merchant')->where('id="'.$coupon_data['merchant_id'].'"')->count();
			if(!$merchant_count)
				$this->error('销售商ID不存在'.'--第'.($k+1).'条数据');

			$coupon_data['is_actived'] = 1;
			
			$coupon_data['actived_time'] = time();
			
			$coupon_data['sold_time'] = strtotime(mb_convert_encoding($v[2], "UTF-8", "GBK"));

			//v($coupon_data);
			if (false === $coupun_model->create($coupon_data)) {
				$this->error($coupun_model->getError().'--第'.($k+1).'条数据');
			}
			
			$coupon_data_arr[] = $coupon_data;	
		}

		if($coupon_data_arr){	
			foreach($coupon_data_arr as $key=>$coupon_each){
				$return  = $coupun_model->save($coupon_each);
				if(!$return){
					$this->error('激活失败'.'--第'.($key+1).'条数据');
				}
			}

			$this->success('批量激活成功！', U("Coupon/index",array('v'=>time())));
			
		}else{
			$this->error('数据为空，批量激活失败！');
		}
	}
}
?>